/**
 * @Date: 2022-03-10 20:07:43
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-13 18:52:30
 * @FilePath: \zhihuReal\controllers\answersCtl.js
 * @Description: 答案控制器
 */
const {
    SuccessModel,
    ErrorModel
} = require('../res-model/index')
const Answer = require('../model/answersMdl')
const User = require('../model/usersMdl')

//获取答案列表
const answerList = async (ctx) => {
    //分页
    const {
        limit = 10, page = 1
    } = ctx.query
    const pagenum = Math.max(+page, 1) - 1
    const limitnum = Math.max(+limit, 1)
    //模糊搜索
    let q = new RegExp(ctx.query.keyword)
    const list = await Answer.find({
        content: q,
        questionId: ctx.params.questionId
    }).limit(limitnum).skip(pagenum * limitnum)
    ctx.body = new SuccessModel(list)
}
//获取单个答案
const oneAnswer = async (ctx) => {
    const {
        fields = ''
    } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const answer = await Answer.findById(ctx.params.id).select(selectFields).populate('answerer')
    if (!answer) {
        ctx.throw(404, '答案不存在')
    } else {
        ctx.body = new SuccessModel(answer)
    }
}
//创建答案
const createAnswer = async (ctx) => {
    ctx.verifyParams({
        content: {
            type: 'string',
            required: true
        },
    })
    const newAnswers = await Answer.create({
        ...ctx.request.body,
        answerer: ctx.state.user._id,
        questionId: ctx.params.questionId
    })
    ctx.status = 204
    ctx.body = new SuccessModel()
}
//更新答案
const updateAnswer = async (ctx) => {
    ctx.verifyParams({
        content: {
            type: 'string',
            required: true
        },
    })
    const newAnswers = await Answer.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    ctx.body = new SuccessModel(newAnswers)
}
//删除答案
const removeAnswer = async (ctx) => {
    const answer = await Answer.findByIdAndRemove(ctx.params.id)
    if (!answer) {
        ctx.throw(404, '你要删除的答案不存在')
    }
    ctx.status = 204

}

module.exports = {
    answerList,
    oneAnswer,
    createAnswer,
    updateAnswer,
    removeAnswer,
}